using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Domain.Token.wand.Token.Entity;
using imitateMacQQ.WebApi.Domain.Token.wand.Token.Interface;
using imitateMacQQ.WebApi.Domain.Token.wand.Token.letter;
using imitateMacQQ.WebApi.Domain.Token.wand.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;

namespace imitateMacQQ.WebApi.Domain.Token.wand.Token.Service;

public class RegisterBeforeAffirm : IAuthentication, IGetTokenService
{
    private JwtHelper JwtHelper { get; set; }

    public RegisterBeforeAffirm(JwtHelper jwtHelper)
    {
        JwtHelper = jwtHelper;
    }

    public User FrontGetSqlAuthentication(LetterFromUsersToBackstage dto,
        out string message, out bool result)
    {
        var user = new User();
        using var db = new DataDbContext();
        result = true;
        var users = db.Users.Where(e => e.Account == dto.Account);

        if (users.Count() > 1)
        {
            message = "Server internal error！User not unique";
            result = false;
            return user;
        }

        if (!users.Any())
        {
            message = "User is nonentity";
            result = false;
            return user;
        }

        foreach (var item in users)
        {
            result = item.Password == dto.Password;
            user = item;
        }

        message = result ? "Login Success" : "Password Error";
        return user;
    }

    public Request<LoginSuccessAccessTokenAndRefreshToken> RegisterGetToken(LetterFromUsersToBackstage dto)
    {
        LoginSuccessAccessTokenAndRefreshToken loginSuccessAccessTokenAndRefreshToken =
            new LoginSuccessAccessTokenAndRefreshToken();
        var res = FrontGetSqlAuthentication(dto, out var message, out var result);

        if (!result)
            return Request<LoginSuccessAccessTokenAndRefreshToken>.Ok(loginSuccessAccessTokenAndRefreshToken, result,
                message);
        loginSuccessAccessTokenAndRefreshToken.Account = res.Account;
        loginSuccessAccessTokenAndRefreshToken.Header = res.Header;
        loginSuccessAccessTokenAndRefreshToken.UserName = res.UserName;
        loginSuccessAccessTokenAndRefreshToken.AccessToken = JwtHelper.CreateToken(res.Account ?? "COMEBACK");
        loginSuccessAccessTokenAndRefreshToken.RefreshToken = JwtHelper.CreateToken(res.Account ?? "COMEBACK", 30000);
        if (loginSuccessAccessTokenAndRefreshToken.AccessToken == "" ||
            loginSuccessAccessTokenAndRefreshToken.RefreshToken == "")
            return Request<LoginSuccessAccessTokenAndRefreshToken>.Ok(null!, false,
                "TOKEN ERROR! CODE 500");
        return Request<LoginSuccessAccessTokenAndRefreshToken>.Ok(loginSuccessAccessTokenAndRefreshToken, result,
            message);
    }
}